package com.umeox.watch.moto.launcher.ui;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.ContentObserver;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.umeox.moto.common.log.Logger;
import com.umeox.moto.watch.themes.app.ThemeAppCompatActivity;
import com.umeox.moto.watch.themes.util.UToast;
import com.umeox.watch.moto.dataservice.DataProvider;
import com.umeox.watch.moto.dataservice.proxy.PushApiClientProxy;
import com.umeox.watch.moto.launcher.R;
import com.umeox.watch.moto.launcher.constant.Constant;
import com.umeox.watch.moto.launcher.event.HorizontalScrollToPagerEvent;
import com.umeox.watch.moto.launcher.utils.ZXingUtils;
import com.umeox.watch.moto.pedometer.util.CacheImpl;

import org.greenrobot.eventbus.EventBus;

public class BindCodeActivity extends ThemeAppCompatActivity {

    private static final String TAG = BindCodeActivity.class.getSimpleName();
    private static final String KEY_LAST_TIME_FETCH_CODE = "last_time_fetch_code";

    private static final int MSG_GO_TO_MAIN = 0x11;


    private ImageView mBindCodeIv;

    private com.umeox.moto.watch.themes.widget.TextView tvBindCode;

    private String mBindCode;
    private BindReceiver mBindReceiver;
    private TextView mSkipTv;

    private PushApiClientProxy apiClientProxy;

    private final ContentObserver mDeviceCodeObserver = new DeviceCodeContentObserver();
    private View mBindSuccessLl;

    public static void launch(Context context) {
        Intent intent = new Intent(context, BindCodeActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    private PushApiClientProxy getApiClientProxy() {
        if (apiClientProxy == null) {
            apiClientProxy = (PushApiClientProxy) PushApiClientProxy.fetchBinder();
        }
        return apiClientProxy;
    }

    private class DeviceCodeContentObserver extends ContentObserver {

        public DeviceCodeContentObserver() {
            super(new Handler());
        }

        @Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);
            mBindCode = DataProvider.getQrCode();
            Logger.e(TAG, "DeviceCodeContentObserver,qrCode=" + mBindCode);
            createCode();
            UToast.show(getResources().getString(R.string.qrcode_refreshed_str), Toast.LENGTH_SHORT);
        }

    }


    private final Handler mHandler = new Handler(new Handler.Callback() {
        @SuppressLint("WrongConstant")
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (msg.what == MSG_GO_TO_MAIN) {
                BindCodeActivity.this.finish();
            }
            return false;
        }
    });


    @SuppressLint("WrongConstant")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bind_code);
        mBindCodeIv = findViewById(R.id.qrImg);
        tvBindCode = findViewById(R.id.tv_bind_code);
        mBindCode = DataProvider.getQrCode();
        Log.d(TAG, "onCreate: " + mBindCode);
        createCode();
        mBindSuccessLl = findViewById(R.id.bind_success_ll);
        mSkipTv = findViewById(R.id.skip_tv);
        DataProvider.DeviceCodeProvider.registerContentObserver(true, mDeviceCodeObserver);
        registerBindReceiver();
        mSkipTv.setOnClickListener(v -> {
            EventBus.getDefault().post(new HorizontalScrollToPagerEvent(1));
            BindCodeActivity.this.finish();
        });
        mBindCodeIv.setOnClickListener(v -> {
            if( (System.currentTimeMillis() - CacheImpl.getInstance().get(KEY_LAST_TIME_FETCH_CODE,0L)) > 5000){
                try {
                    getApiClientProxy().requestGetBindCode();
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                CacheImpl.getInstance().put(KEY_LAST_TIME_FETCH_CODE,System.currentTimeMillis());
            }
        });

    }


    private void registerBindReceiver() {
        mBindReceiver = new BindReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constant.IntentConstant.INTENT_ACTIVE);
        intentFilter.addAction(Constant.IntentConstant.MQTT_CONNECTED);
        registerReceiver(mBindReceiver, intentFilter);
    }


    public void createCode() {
        if (mBindCode == null || mBindCodeIv == null) return;

        try {
            Bitmap codeBitmap = ZXingUtils.createQRCode(mBindCode, 100, 100);
            mBindCodeIv.setImageBitmap(codeBitmap);
            tvBindCode.setText(getString(R.string.k2_invite_follower_binding_code, mBindCode));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mDeviceCodeObserver != null) {
            getContentResolver().unregisterContentObserver(mDeviceCodeObserver);
        }
        if (mBindReceiver != null) {
            unregisterReceiver(mBindReceiver);
            mBindReceiver = null;
        }
    }

    private class BindReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (TextUtils.isEmpty(action)) {
                return;
            }

            if (action.equals(Constant.IntentConstant.INTENT_ACTIVE)) {
                mBindSuccessLl.setVisibility(View.VISIBLE);
                mHandler.sendEmptyMessageDelayed(MSG_GO_TO_MAIN, 1000);
            }
        }
    }


}
